# Copyright 2005 Daniel Henninger <jadestorm@nc.rr.com>
# Licensed for distribution under the GPL version 2, check COPYING for details

import utils
if utils.checkTwisted():
	from twisted.xish.domish import Element
	from twisted.words.protocols.jabber import jid
else:
	from tlib.domish import Element
	from tlib.jabber import jid
import debug
import config
import disco
import lang
import re
import globals
from tlib import oscar



def sendCancellation(pytrans, node, el, sessionid=None):
	to = el.getAttribute("from")
	ID = el.getAttribute("id")
	ulang = utils.getLang(el)

	iq = Element((None, "iq"))
	iq.attributes["to"] = to
	iq.attributes["from"] = config.jid
	if ID:
		iq.attributes["id"] = ID
	iq.attributes["type"] = "result"

	command = iq.addElement("command")
	if sessionid:
		command.attributes["sessionid"] = sessionid
	else:
		command.attributes["sessionid"] = pytrans.makeMessageID()
	command.attributes["node"] = node
	command.attributes["xmlns"] = globals.COMMANDS
	command.attributes["status"] = "canceled"

	pytrans.send(iq)



def sendError(pytrans, node, el, errormsg, sessionid=None):
	to = el.getAttribute("from")
	ID = el.getAttribute("id")
	ulang = utils.getLang(el)

	iq = Element((None, "iq"))
	iq.attributes["to"] = to
	iq.attributes["from"] = config.jid
	if ID:
		iq.attributes["id"] = ID
	iq.attributes["type"] = "result"

	command = iq.addElement("command")
	if sessionid:
		command.attributes["sessionid"] = sessionid
	else:
		command.attributes["sessionid"] = pytrans.makeMessageID()
	command.attributes["node"] = node
	command.attributes["xmlns"] = globals.COMMANDS
	command.attributes["status"] = "completed"

	note = command.addElement("note")
	note.attributes["type"] = "error"
	note.addContent(errormsg)

	pytrans.send(iq)



class ChangePassword:
	def __init__(self, pytrans):
		self.pytrans = pytrans
		self.pytrans.adHocCommands.addCommand("changepassword", self.incomingIq, "command_ChangePassword")

	def incomingIq(self, el):
		to = el.getAttribute("from")
		toj = jid.JID(to)
		ID = el.getAttribute("id")
		ulang = utils.getLang(el)

		sessionid = None
		oldpassword = None
		newpassword = None
		newpasswordagain = None

		for command in el.elements():
			sessionid = command.getAttribute("sessionid")
			if command.getAttribute("action") == "cancel":
				sendCancellation(self.pytrans, "changepassword", el, sessionid)
				return
			for child in command.elements():
				if child.name == "x" and child.getAttribute("type") == "submit":
					for field in child.elements():
						if field.name == "field" and field.getAttribute("var") == "newpassword":
							for value in field.elements():
								if value.name == "value":
									newpassword = value.__str__()
						elif field.name == "field" and field.getAttribute("var") == "newpasswordagain":
							for value in field.elements():
								if value.name == "value":
									newpasswordagain = value.__str__()
						elif field.name == "field" and field.getAttribute("var") == "oldpassword":
							for value in field.elements():
								if value.name == "value":
									oldpassword = value.__str__()

		if not self.pytrans.sessions.has_key(toj.userhost()):
			sendError(self.pytrans, "changepassword", el, errormsg=lang.get("command_NoSession", ulang), sessionid=sessionid)
		elif newpassword and newpassword != newpasswordagain:
			debug.log("newpassword = %s and newpasswordagain = %s" % (newpassword, newpasswordagain))
			self.sendForm(el, sessionid=sessionid, errormsg=lang.get("command_ChangePassword_Mismatch", ulang))
		elif oldpassword and newpassword:
			self.changePassword(el, oldpassword, newpassword, sessionid)
		else:
			self.sendForm(el)

	def sendForm(self, el, sessionid=None, errormsg=None):
		to = el.getAttribute("from")
		ID = el.getAttribute("id")
		ulang = utils.getLang(el)

		iq = Element((None, "iq"))
		iq.attributes["to"] = to
		iq.attributes["from"] = config.jid
		if ID:
			iq.attributes["id"] = ID
		iq.attributes["type"] = "result"

		command = iq.addElement("command")
		if sessionid:
			command.attributes["sessionid"] = sessionid
		else:
			command.attributes["sessionid"] = self.pytrans.makeMessageID()
		command.attributes["node"] = "changepassword"
		command.attributes["xmlns"] = globals.COMMANDS
		command.attributes["status"] = "executing"

		if errormsg:
			note = command.addElement("note")
			note.attributes["type"] = "error"
			note.addContent(errormsg)

		actions = command.addElement("actions")
		actions.attributes["execute"] = "complete"
		actions.addElement("complete")

		x = command.addElement("x")
		x.attributes["xmlns"] = "jabber:x:data"
		x.attributes["type"] = "form"

		title = x.addElement("title")
		title.addContent(lang.get("command_ChangePassword", ulang))

		instructions = x.addElement("instructions")
		instructions.addContent(lang.get("command_ChangePassword_Instructions", ulang))

		oldpassword = x.addElement("field")
		oldpassword.attributes["type"] = "text-private"
		oldpassword.attributes["var"] = "oldpassword"
		oldpassword.attributes["label"] = lang.get("command_ChangePassword_OldPassword", ulang)

		newpassword = x.addElement("field")
		newpassword.attributes["type"] = "text-private"
		newpassword.attributes["var"] = "newpassword"
		newpassword.attributes["label"] = lang.get("command_ChangePassword_NewPassword", ulang)

		newpassworda = x.addElement("field")
		newpassworda.attributes["type"] = "text-private"
		newpassworda.attributes["var"] = "newpasswordagain"
		newpassworda.attributes["label"] = lang.get("command_ChangePassword_NewPasswordAgain", ulang)

		self.pytrans.send(iq)

	def changePassword(self, el, oldpassword, newpassword, sessionid):
		to = el.getAttribute("from")
		toj = jid.JID(to)

		self.pytrans.sessions[toj.userhost()].legacycon.bos.changePassword(oldpassword, newpassword).addCallback(self.pwdChangeResults, el, sessionid, newpassword)

	def pwdChangeResults(self, results, el, sessionid, newpassword):
		debug.log("pwdChange %s" % (str(results)))
		to = el.getAttribute("from")
		toj = jid.JID(to)
		ID = el.getAttribute("id")
		ulang = utils.getLang(el)

		iq = Element((None, "iq"))
		iq.attributes["to"] = to
		iq.attributes["from"] = config.jid
		if ID:
			iq.attributes["id"] = ID
		iq.attributes["type"] = "result"

		command = iq.addElement("command")
		if sessionid:
			command.attributes["sessionid"] = sessionid
		else:
			command.attributes["sessionid"] = self.pytrans.makeMessageID()
		command.attributes["node"] = "changepassword"
		command.attributes["xmlns"] = globals.COMMANDS
		command.attributes["status"] = "completed"

		note = command.addElement("note")
		if results[3]:
			note.attributes["type"] = "error"
			note.addContent(lang.get("command_ChangePassword_Failed", ulang))
		else:
			note.attributes["type"] = "info"
			note.addContent(lang.get("command_Done", ulang))
			(username, oldpassword) = self.pytrans.xdb.getRegistration(toj.userhost())
			self.pytrans.xdb.setRegistration(toj.userhost(), username, newpassword)

		self.pytrans.send(iq)



class ChangeEmail:
	def __init__(self, pytrans):
		self.pytrans = pytrans
		self.pytrans.adHocCommands.addCommand("changeemail", self.incomingIq, "command_ChangeEmail")

	def incomingIq(self, el):
		to = el.getAttribute("from")
		toj = jid.JID(to)
		ID = el.getAttribute("id")
		ulang = utils.getLang(el)

		sessionid = None
		email = None

		for command in el.elements():
			sessionid = command.getAttribute("sessionid")
			if command.getAttribute("action") == "cancel":
				sendCancellation(self.pytrans, "changeemail", el, sessionid)
				return
			for child in command.elements():
				if child.name == "x" and child.getAttribute("type") == "submit":
					for field in child.elements():
						if field.name == "field" and field.getAttribute("var") == "email":
							for value in field.elements():
								if value.name == "value":
									email = value.__str__()

		if not self.pytrans.sessions.has_key(toj.userhost()):
			sendError(self.pytrans, "changeemail", el, errormsg=lang.get("command_NoSession", ulang), sessionid=sessionid)
		elif email:
			self.changeEmail(el, email, sessionid)
		else:
			self.pytrans.sessions[toj.userhost()].legacycon.bos.getEmailAddress().addCallback(self.sendForm, el)

	def sendForm(self, current, el, sessionid=None, errormsg=None):
		to = el.getAttribute("from")
		ID = el.getAttribute("id")
		ulang = utils.getLang(el)

		iq = Element((None, "iq"))
		iq.attributes["to"] = to
		iq.attributes["from"] = config.jid
		if ID:
			iq.attributes["id"] = ID
		iq.attributes["type"] = "result"

		command = iq.addElement("command")
		if sessionid:
			command.attributes["sessionid"] = sessionid
		else:
			command.attributes["sessionid"] = self.pytrans.makeMessageID()
		command.attributes["node"] = "changeemail"
		command.attributes["xmlns"] = globals.COMMANDS
		command.attributes["status"] = "executing"

		if errormsg:
			note = command.addElement("note")
			note.attributes["type"] = "error"
			note.addContent(errormsg)

		actions = command.addElement("actions")
		actions.attributes["execute"] = "complete"
		actions.addElement("complete")

		x = command.addElement("x")
		x.attributes["xmlns"] = "jabber:x:data"
		x.attributes["type"] = "form"

		title = x.addElement("title")
		title.addContent(lang.get("command_ChangeEmail", ulang))

		instructions = x.addElement("instructions")
		instructions.addContent(lang.get("command_ChangeEmail_Instructions", ulang))

		email = x.addElement("field")
		email.attributes["type"] = "text-single"
		email.attributes["var"] = "email"
		email.attributes["label"] = lang.get("command_ChangeEmail_Email", ulang)
		if current[4]:
			email.addElement("value").addContent(current[4])

		self.pytrans.send(iq)

	def changeEmail(self, el, email, sessionid):
		to = el.getAttribute("from")
		toj = jid.JID(to)

		self.pytrans.sessions[toj.userhost()].legacycon.bos.changeEmail(email).addCallback(self.emailChangeResults, el, sessionid)

	def emailChangeResults(self, results, el, sessionid):
		debug.log("emailChange %s" % (str(results)))
		to = el.getAttribute("from")
		toj = jid.JID(to)
		ID = el.getAttribute("id")
		ulang = utils.getLang(el)

		iq = Element((None, "iq"))
		iq.attributes["to"] = to
		iq.attributes["from"] = config.jid
		if ID:
			iq.attributes["id"] = ID
		iq.attributes["type"] = "result"

		command = iq.addElement("command")
		if sessionid:
			command.attributes["sessionid"] = sessionid
		else:
			command.attributes["sessionid"] = self.pytrans.makeMessageID()
		command.attributes["node"] = "changeemail"
		command.attributes["xmlns"] = globals.COMMANDS
		command.attributes["status"] = "completed"

		note = command.addElement("note")
		if results[3]:
			note.attributes["type"] = "error"
			note.addContent(results[3][1])
		else:
			note.attributes["type"] = "info"
			note.addContent(lang.get("command_Done", ulang))

		self.pytrans.send(iq)



class FormatScreenName:
	def __init__(self, pytrans):
		self.pytrans = pytrans
		self.pytrans.adHocCommands.addCommand("formatscreenname", self.incomingIq, "command_FormatScreenName")

	def incomingIq(self, el):
		to = el.getAttribute("from")
		toj = jid.JID(to)
		ID = el.getAttribute("id")
		ulang = utils.getLang(el)

		sessionid = None
		fmtsn = None

		for command in el.elements():
			sessionid = command.getAttribute("sessionid")
			if command.getAttribute("action") == "cancel":
				sendCancellation(self.pytrans, "formatscreenname", el, sessionid)
				return
			for child in command.elements():
				if child.name == "x" and child.getAttribute("type") == "submit":
					for field in child.elements():
						if field.name == "field" and field.getAttribute("var") == "fmtsn":
							for value in field.elements():
								if value.name == "value":
									fmtsn = value.__str__()

		if not self.pytrans.sessions.has_key(toj.userhost()):
			sendError(self.pytrans, "formatscreenname", el, errormsg=lang.get("command_NoSession", ulang), sessionid=sessionid)
		elif fmtsn:
			self.changeSNFormat(el, fmtsn, sessionid)
		else:
			self.pytrans.sessions[toj.userhost()].legacycon.bos.getFormattedScreenName().addCallback(self.sendForm, el)

	def sendForm(self, current, el, sessionid=None, errormsg=None):
		to = el.getAttribute("from")
		ID = el.getAttribute("id")
		ulang = utils.getLang(el)

		iq = Element((None, "iq"))
		iq.attributes["to"] = to
		iq.attributes["from"] = config.jid
		if ID:
			iq.attributes["id"] = ID
		iq.attributes["type"] = "result"

		command = iq.addElement("command")
		if sessionid:
			command.attributes["sessionid"] = sessionid
		else:
			command.attributes["sessionid"] = self.pytrans.makeMessageID()
		command.attributes["node"] = "formatscreenname"
		command.attributes["xmlns"] = globals.COMMANDS
		command.attributes["status"] = "executing"

		if errormsg:
			note = command.addElement("note")
			note.attributes["type"] = "error"
			note.addContent(errormsg)

		actions = command.addElement("actions")
		actions.attributes["execute"] = "complete"
		actions.addElement("complete")

		x = command.addElement("x")
		x.attributes["xmlns"] = "jabber:x:data"
		x.attributes["type"] = "form"

		title = x.addElement("title")
		title.addContent(lang.get("command_FormatScreenName", ulang))

		instructions = x.addElement("instructions")
		instructions.addContent(lang.get("command_FormatScreenName_Instructions", ulang))

		fmtsn = x.addElement("field")
		fmtsn.attributes["type"] = "text-single"
		fmtsn.attributes["var"] = "fmtsn"
		fmtsn.attributes["label"] = lang.get("command_FormatScreenName_FMTScreenName", ulang)
		if current[1]:
			fmtsn.addElement("value").addContent(current[1])

		self.pytrans.send(iq)

	def changeSNFormat(self, el, fmtsn, sessionid):
		to = el.getAttribute("from")
		toj = jid.JID(to)

		debug.log("Got screen name [%s]" % fmtsn)
		self.pytrans.sessions[toj.userhost()].legacycon.bos.changeScreenNameFormat(fmtsn).addCallback(self.snfmtChangeResults, el, sessionid)

	def snfmtChangeResults(self, results, el, sessionid):
		debug.log("snfmtChange %s" % (str(results)))
		to = el.getAttribute("from")
		toj = jid.JID(to)
		ID = el.getAttribute("id")
		ulang = utils.getLang(el)

		iq = Element((None, "iq"))
		iq.attributes["to"] = to
		iq.attributes["from"] = config.jid
		if ID:
			iq.attributes["id"] = ID
		iq.attributes["type"] = "result"

		command = iq.addElement("command")
		if sessionid:
			command.attributes["sessionid"] = sessionid
		else:
			command.attributes["sessionid"] = self.pytrans.makeMessageID()
		command.attributes["node"] = "formatscreenname"
		command.attributes["xmlns"] = globals.COMMANDS
		command.attributes["status"] = "completed"

		note = command.addElement("note")
		if results[3]:
			note.attributes["type"] = "error"
			note.addContent(results[3][1])
		else:
			note.attributes["type"] = "info"
			note.addContent(lang.get("command_Done", ulang))

		self.pytrans.send(iq)



class EmailLookup:
	def __init__(self, pytrans):
		self.pytrans = pytrans
		self.pytrans.adHocCommands.addCommand("emaillookup", self.incomingIq, "command_EmailLookup")

	def incomingIq(self, el):
		to = el.getAttribute("from")
		toj = jid.JID(to)
		ID = el.getAttribute("id")
		ulang = utils.getLang(el)

		sessionid = None
		email = None

		for command in el.elements():
			sessionid = command.getAttribute("sessionid")
			if command.getAttribute("action") == "cancel":
				sendCancellation(self.pytrans, "emaillookup", el, sessionid)
				return
			for child in command.elements():
				if child.name == "x" and child.getAttribute("type") == "submit":
					for field in child.elements():
						if field.name == "field" and field.getAttribute("var") == "email":
							for value in field.elements():
								if value.name == "value":
									email = value.__str__()

		if not self.pytrans.sessions.has_key(toj.userhost()):
			sendError(self.pytrans, "emaillookup", el, errormsg=lang.get("command_NoSession", ulang), sessionid=sessionid)
		elif email:
			self.lookupEmail(el, email, sessionid=sessionid)
		else:
			self.sendForm(el)

	def sendForm(self, el, sessionid=None, errormsg=None):
		to = el.getAttribute("from")
		ID = el.getAttribute("id")
		ulang = utils.getLang(el)

		iq = Element((None, "iq"))
		iq.attributes["to"] = to
		iq.attributes["from"] = config.jid
		if ID:
			iq.attributes["id"] = ID
		iq.attributes["type"] = "result"

		command = iq.addElement("command")
		if sessionid:
			command.attributes["sessionid"] = sessionid
		else:
			command.attributes["sessionid"] = self.pytrans.makeMessageID()
		command.attributes["node"] = "emaillookup"
		command.attributes["xmlns"] = globals.COMMANDS
		command.attributes["status"] = "executing"

		if errormsg:
			note = command.addElement("note")
			note.attributes["type"] = "error"
			note.addContent(errormsg)

		actions = command.addElement("actions")
		actions.attributes["execute"] = "complete"
		actions.addElement("complete")

		x = command.addElement("x")
		x.attributes["xmlns"] = "jabber:x:data"
		x.attributes["type"] = "form"

		title = x.addElement("title")
		title.addContent(lang.get("command_EmailLookup", ulang))

		instructions = x.addElement("instructions")
		instructions.addContent(lang.get("command_EmailLookup_Instructions", ulang))

		email = x.addElement("field")
		email.attributes["type"] = "text-single"
		email.attributes["var"] = "email"
		email.attributes["label"] = lang.get("command_EmailLookup_Email", ulang)

		self.pytrans.send(iq)

	def lookupEmail(self, el, email, sessionid=None):
		to = el.getAttribute("from")
		toj = jid.JID(to)

		self.pytrans.sessions[toj.userhost()].legacycon.bos.lookupEmail(email).addCallback(self.emailLookupResults, el, sessionid)

	def emailLookupResults(self, results, el, sessionid):
		debug.log("emailLookupResults %s" % (str(results)))
		to = el.getAttribute("from")
		toj = jid.JID(to)
		ID = el.getAttribute("id")
		ulang = utils.getLang(el)

		iq = Element((None, "iq"))
		iq.attributes["to"] = to
		iq.attributes["from"] = config.jid
		if ID:
			iq.attributes["id"] = ID
		iq.attributes["type"] = "result"

		command = iq.addElement("command")
		if sessionid:
			command.attributes["sessionid"] = sessionid
		else:
			command.attributes["sessionid"] = self.pytrans.makeMessageID()
		command.attributes["node"] = "emaillookup"
		command.attributes["xmlns"] = globals.COMMANDS
		command.attributes["status"] = "completed"

		note = command.addElement("note")
		note.attributes["type"] = "info"
		note.addContent(lang.get("command_EmailLookup_Results", ulang))

		x = command.addElement("x")
		x.attributes["xmlns"] = "jabber:x:data"
		x.attributes["type"] = "form"

		title = x.addElement("title")
		title.addContent(lang.get("command_EmailLookup", ulang))

		for r in results:
			email = x.addElement("field")
			email.attributes["type"] = "fixed"
			email.addElement("value").addContent(r)

		self.pytrans.send(iq)



class ConfirmAccount:
	def __init__(self, pytrans):
		self.pytrans = pytrans
		self.pytrans.adHocCommands.addCommand("confirmaccount", self.incomingIq, "command_ConfirmAccount")

	def incomingIq(self, el):
		to = el.getAttribute("from")
		toj = jid.JID(to)
		ID = el.getAttribute("id")
		ulang = utils.getLang(el)

		sessionid = None

		for command in el.elements():
			sessionid = command.getAttribute("sessionid")
			if command.getAttribute("action") == "cancel":
				sendCancellation(self.pytrans, "confirmaccount", el, sessionid)
				return

		if not self.pytrans.sessions.has_key(toj.userhost()):
			sendError(self.pytrans, "confirmaccount", el, errormsg=lang.get("command_NoSession", ulang), sessionid=sessionid)
		else:
			self.pytrans.sessions[toj.userhost()].legacycon.bos.confirmAccount().addCallback(self.sendResponse, el, sessionid)

	def sendResponse(self, failure, el, sessionid=None):
		debug.log("confirmAccount %s" % (str(failure)))
		to = el.getAttribute("from")
		toj = jid.JID(to)
		ID = el.getAttribute("id")
		ulang = utils.getLang(el)

		iq = Element((None, "iq"))
		iq.attributes["to"] = to
		iq.attributes["from"] = config.jid
		if ID:
			iq.attributes["id"] = ID
		iq.attributes["type"] = "result"

		command = iq.addElement("command")
		if sessionid:
			command.attributes["sessionid"] = sessionid
		else:
			command.attributes["sessionid"] = self.pytrans.makeMessageID()
		command.attributes["node"] = "confirmaccount"
		command.attributes["xmlns"] = globals.COMMANDS
		command.attributes["status"] = "completed"

		note = command.addElement("note")
		if failure:
			note.attributes["type"] = "error"
			note.addContent(lang.get("command_ConfirmAccount_Failed", ulang))
		else:
			note.attributes["type"] = "info"
			note.addContent(lang.get("command_ConfirmAccount_Complete", ulang))

		self.pytrans.send(iq)



class AIMURITranslate:
	def __init__(self, pytrans):
		self.pytrans = pytrans
		self.pytrans.adHocCommands.addCommand("aimuritranslate", self.incomingIq, "command_AIMURITranslate")

	def incomingIq(self, el):
		to = el.getAttribute("from")
		toj = jid.JID(to)
		ID = el.getAttribute("id")
		ulang = utils.getLang(el)

		sessionid = None
		uri = None

		for command in el.elements():
			sessionid = command.getAttribute("sessionid")
			if command.getAttribute("action") == "cancel":
				sendCancellation(self.pytrans, "aimuritranslate", el, sessionid)
				return
			for child in command.elements():
				if child.name == "x" and child.getAttribute("type") == "submit":
					for field in child.elements():
						if field.name == "field" and field.getAttribute("var") == "uri":
							for value in field.elements():
								if value.name == "value":
									uri = value.__str__()

		if not self.pytrans.sessions.has_key(toj.userhost()):
			sendError(self.pytrans, "aimuritranslate", el, errormsg=lang.get("command_NoSession", ulang), sessionid=sessionid)
		elif uri:
			self.translateUri(el, uri, sessionid=sessionid)
		else:
			self.sendForm(el)

	def sendForm(self, el, sessionid=None, errormsg=None):
		to = el.getAttribute("from")
		ID = el.getAttribute("id")
		ulang = utils.getLang(el)

		iq = Element((None, "iq"))
		iq.attributes["to"] = to
		iq.attributes["from"] = config.jid
		if ID:
			iq.attributes["id"] = ID
		iq.attributes["type"] = "result"

		command = iq.addElement("command")
		if sessionid:
			command.attributes["sessionid"] = sessionid
		else:
			command.attributes["sessionid"] = self.pytrans.makeMessageID()
		command.attributes["node"] = "aimuritranslate"
		command.attributes["xmlns"] = globals.COMMANDS
		command.attributes["status"] = "executing"

		if errormsg:
			note = command.addElement("note")
			note.attributes["type"] = "error"
			note.addContent(errormsg)

		actions = command.addElement("actions")
		actions.attributes["execute"] = "complete"
		actions.addElement("complete")

		x = command.addElement("x")
		x.attributes["xmlns"] = "jabber:x:data"
		x.attributes["type"] = "form"

		title = x.addElement("title")
		title.addContent(lang.get("command_AIMURITranslate", ulang))

		instructions = x.addElement("instructions")
		instructions.addContent(lang.get("command_AIMURITranslate_Instructions", ulang))

		email = x.addElement("field")
		email.attributes["type"] = "text-single"
		email.attributes["var"] = "uri"
		email.attributes["label"] = lang.get("command_AIMURITranslate_URI", ulang)

		self.pytrans.send(iq)

	def translateUri(self, el, uri, sessionid=None):
		to = el.getAttribute("from")
		toj = jid.JID(to)
		ID = el.getAttribute("id")
		ulang = utils.getLang(el)

		iq = Element((None, "iq"))
		iq.attributes["to"] = to
		iq.attributes["from"] = config.jid
		if ID:
			iq.attributes["id"] = ID
		iq.attributes["type"] = "result"

		command = iq.addElement("command")
		if sessionid:
			command.attributes["sessionid"] = sessionid
		else:
			command.attributes["sessionid"] = self.pytrans.makeMessageID()
		command.attributes["node"] = "aimuritranslate"
		command.attributes["xmlns"] = globals.COMMANDS
		command.attributes["status"] = "completed"

		session = self.pytrans.sessions[toj.userhost()]

		m = re.match('\s*aim:([^\?]+)\?([^\s]+)\s*', uri)
		handled = False
		if m != None:
			cmd = m.group(1)
			cmd = cmd.lower() # I don't like case-sensitive cmds
			payload = m.group(2)
			pieces = payload.split("&")
			options = {}
			for p in pieces:
				if not p or p.find("=") == -1: continue
				option,value = p.split("=", 2)
				option = option.lower() # Ditto
				options[option] = value
			if cmd == "buddyicon":
				# What the hell?
				# aim:BuddyIcon?Src=http://cdn-aimtoday.aol.com/aimtoday_buddyicons/inside_aol_1
				# It's a buddy icon alright, but..?
				# Maybe this sets your buddy icon?
				pass
			elif cmd == "gochat":
				# Ah yes, a chatroom, lets invite the submitter
				roomname = options.get('roomname', None)
				if roomname:
					exchange = options.get('exchange', 4)
					debug.log("Sending invite to %s (%d)" % (roomname, int(exchange)))
					from glue import aim2jid, LegacyGroupchat
					groupchat = LegacyGroupchat(session=session, resource=session.highestResource(), ID=roomname.replace(' ','_')+"%"+str(exchange))
					groupchat.sendUserInvite(config.jid)
					handled = True
			elif cmd == "goim":
				# Send a message, to yourself, or someone else
				from glue import aim2jid
				message = options.get('message', None)
				screenname = options.get('screenname', None)
				if message:
					if screenname:
						# send message to someone else
						debug.log("Sending message to %s: %s" % (screenname, message))
						text = oscar.dehtml(message)
						text = text.strip()
						session.legacycon.sendMessage(aim2jid(screenname), None, text, False, utils.prepxhtml(message))
						handled = True
					else:
						# send message to self
						debug.log("Sending message to self: %s" % (message))
						text = oscar.dehtml(message)
						text = text.strip()
						session.sendMessage(to=toj.userhost(), fro=config.jid, body=text, mtype="chat", xhtml=utils.prepxhtml(message))
						handled = True

		note = command.addElement("note")
		if not handled:
			note.attributes["type"] = "error"
			note.addContent(lang.get("command_AIMURITranslate_Failed", ulang))
		else:
			note.attributes["type"] = "info"
			note.addContent(lang.get("command_Done", ulang))

		self.pytrans.send(iq)
